package com.hbzhou.open.camera;

import com.hbzhou.open.camera.listener.PermissionInterface;
import com.hbzhou.open.camera.slice.WelcomeAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.security.SystemPermission;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

public class MainAbility extends Ability {
    /**
     * REQ PERMISSION CODE
     */
    public static final int REQ_PERMISSION_CODE = 1001;

    private PermissionInterface mPermissionListener;
    private List<String> mPermissions =
            new LinkedList<>(
                    Arrays.asList(
                            SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE));

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(WelcomeAbilitySlice.class.getName());
        reqPermissions();
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    private void reqPermissions() {
        mPermissions.removeIf(perM -> verifySelfPermission(perM) == PERMISSION_GRANTED || !canRequestPermission(perM));
        if (!mPermissions.isEmpty()) {
            requestPermissionsFromUser(
                    mPermissions.toArray(new String[mPermissions.size()]), MainAbility.REQ_PERMISSION_CODE);
        }
    }

    /**
     * set Permission Listener
     *
     * @param permissionListener PermissionInterface
     */
    public void setPermissionListener(PermissionInterface permissionListener) {
        this.mPermissionListener = permissionListener;
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] ss, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, ss, grantResults);
        if (requestCode != REQ_PERMISSION_CODE) {
            return;
        }
        boolean isHavePermission = false;
        for (int i = 0; i < ss.length; i++) {
            isHavePermission = grantResults[i] == PERMISSION_GRANTED;
        }
        if (isHavePermission) {
            restart();
        }
    }
}
